/*
 * @Description: 公共model
 * @Author: franktrue 807615827@qq.com
 * @Date: 2021-07-28 08:08:31
 * @LastEditTime: 2021-07-31 12:02:18
 */
package model

import (
	"database/sql"
	"fmt"
	"github.com/franktrue/blog-service/global"
	"github.com/franktrue/blog-service/pkg/setting"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

type Model struct {
	ID        uint32 `gorm:"primary_key" json:"id"`
	CreatedBy string `json:"created_by"`
	UpdatedBy string `json:"updated_by"`
	CreatedAt uint32 `gorm:"autoCreateTime" json:"created_at"`
	UpdatedAt uint32 `gorm:"autoUpdateTime" json:"updated_at"`
	DeletedAt uint32 `json:"deleted_at"`
}

func NewDBEngine(databaseSetting *setting.DatabaseSettingS) (db *gorm.DB, err error) {
	s := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=%s&parseTime=%t&loc=Local",
		databaseSetting.Username,
		databaseSetting.Password,
		databaseSetting.Host,
		databaseSetting.DBName,
		databaseSetting.Charset,
		databaseSetting.ParseTime,
	)
	db, err = gorm.Open(mysql.Open(s), &gorm.Config{})
	if err != nil {
		return nil, err
	}

	if global.ServerSetting.RunMode == "debug" {
		db = db.Debug()
	}

	var sqlDB *sql.DB
	sqlDB, err = db.DB()
	if err != nil {
		return nil, err
	}
	sqlDB.SetMaxIdleConns(databaseSetting.MaxIdleConns)
	sqlDB.SetMaxOpenConns(databaseSetting.MaxOpenConns)

	return db, nil
}
